package com.zxx.dis.factory;

import com.zxx.dis.core.DistributedLockFactory;
import com.zxx.dis.lock.RedisDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Component
public class RedisDistributedLockFactory implements DistributedLockFactory {
    @Autowired
    private final StringRedisTemplate redisTemplate;

    private static final long DEFAULT_EXPIRE_TIME = 30L;
    private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;
    private static String uuid;

    public RedisDistributedLockFactory(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.uuid = UUID.randomUUID().toString();
    }

    @Override
    public Lock createLock(String lockKey) {
        return createLock(lockKey, DEFAULT_EXPIRE_TIME, DEFAULT_TIME_UNIT);
    }

    @Override
    public Lock createLock(String lockKey, long expireTime, TimeUnit timeUnit) {
//        return null;
        return new RedisDistributedLock(redisTemplate, lockKey, expireTime, timeUnit, this.uuid);
    }
}
